package cn.xd.itstack.springframework.beans.factory.support;


import cn.xd.itstack.springframework.beans.BeansException;
import cn.xd.itstack.springframework.beans.factory.DisposableBean;
import cn.xd.itstack.springframework.beans.factory.config.SingletonBeanRegistry;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Classname DefaultSingletonBeanRegistry
 * @Description TODO
 * @Date 2022/5/10 下午3:54
 * @Created by lvxiaodong
 */
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    protected static final Object NULL_OBJECT = new Object();

    private Map<String, Object> singletonBeanMap =new HashMap<>();

    private final Map<String, DisposableBean> disposableBeans = new HashMap<>();

    @Override
    public Object getSingleton(String beanName) {
        return singletonBeanMap.get(beanName);
    }
    public void registerSingleton(String beanName, Object singletonObject) {
        singletonBeanMap.put(beanName, singletonObject);
    }

    protected  void addSingleton(String beanName,Object Bean){
        singletonBeanMap.put(beanName,Bean);
    }

    protected void registerDisposableBean(String beanName, DisposableBean disposableBean){
        disposableBeans.put(beanName,disposableBean);
    }

    public void destroySingletons() {
        Set<String> disposableBeanNameSet = disposableBeans.keySet();
        Object[] disposableBeanNames = disposableBeanNameSet.toArray();
        for (Object disposableBeanName:disposableBeanNames) {
            DisposableBean remove = disposableBeans.remove(disposableBeanName);
            try {
                remove.destroy();
            } catch (Exception e) {
                throw new BeansException("Destroy method on bean with name '" + remove + "' threw an exception", e);
            }
        }


    }
}
